package cn.tedu.acquisition.controller.handler;

import cn.tedu.acquisition.ex.ServiceException;
import cn.tedu.acquisition.ex.UsernameDuplicateException;
import cn.tedu.acquisition.web.JsonResult;
import cn.tedu.acquisition.web.State;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * @Author 得物项目组
 * @Date 2022/6/7 9:13
 * @Version 1.0
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(ServiceException.class)
    public JsonResult<Void> handleServiceException(ServiceException e) {
        // 首先判断抛出的异常是不是UsernameDuplicateException异常
        // 如果是，则返回用户名错误的信息
        if (e instanceof UsernameDuplicateException) {
            return JsonResult.fail(State.ERR_USERNAME, e.getMessage());
        } else {
            return JsonResult.fail(State.ERR_INSERT, e.getMessage());
        }
    }

    @ExceptionHandler(BindException.class)
    public JsonResult<Void> handleBindException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();
        String message = bindingResult.getFieldError().getDefaultMessage();
        return JsonResult.fail(State.ERR_BAN_REQUEST,message);
    }
}
